package handler

import (
	"fitness/go-admin/internal/model"
	"fitness/go-admin/internal/service"
	"fitness/go-admin/pkg/errcode"
	"fitness/go-admin/pkg/logger"
	"fitness/go-admin/pkg/response"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

type OperationLogHandler struct {
	service service.OperationLogService
}

func NewOperationLogHandler(service service.OperationLogService) *OperationLogHandler {
	return &OperationLogHandler{service: service}
}

// List 获取操作日志列表
// @Summary 获取操作日志列表
// @Tags 操作日志管理
// @Produce json
// @Param page query int false "页码" default(1)
// @Param pageSize query int false "每页数量" default(10)
// @Param username query string false "用户名"
// @Param action query string false "操作类型"
// @Param resource query string false "资源类型"
// @Param ip query string false "IP地址"
// @Param startDate query string false "开始日期(YYYY-MM-DD)"
// @Param endDate query string false "结束日期(YYYY-MM-DD)"
// @Success 200 {object} response.PageResponse
// @Router /api/v1/operation-logs [get]
func (h *OperationLogHandler) List(c *gin.Context) {
	var req model.OperationLogListReq
	if err := c.ShouldBindQuery(&req); err != nil {
		response.Error(c, errcode.BadRequest, "参数错误: "+err.Error())
		return
	}

	// 设置默认值
	if req.Page == 0 {
		req.Page = 1
	}
	if req.PageSize == 0 {
		req.PageSize = 10
	}

	logs, total, err := h.service.GetLogList(&req)
	if err != nil {
		logger.Error("获取操作日志列表失败", "error", err.Error())
		response.Error(c, errcode.InternalError, err.Error())
		return
	}

	// 记录审计日志
	adminID, _ := c.Get("userId")
	logger.LogAudit(logger.AuditLog{
		UserID:    adminID.(uint),
		Action:    "VIEW_OPERATION_LOG_LIST",
		Resource:  "operation_log",
		IP:        c.ClientIP(),
		UserAgent: c.GetHeader("User-Agent"),
		Details:   "查询参数: " + c.Request.URL.RawQuery,
	})

	response.SuccessWithPage(c, logs, total, req.Page, req.PageSize, "获取成功")
}

// Get 获取操作日志详情
// @Summary 获取操作日志详情
// @Tags 操作日志管理
// @Produce json
// @Param id path int true "日志ID"
// @Success 200 {object} response.Response{data=model.OperationLogDetailResp}
// @Router /api/v1/operation-logs/{id} [get]
func (h *OperationLogHandler) Get(c *gin.Context) {
	// 获取日志ID参数
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		response.Error(c, errcode.BadRequest, "日志ID格式错误")
		return
	}

	// 调用Service层获取详情
	detail, err := h.service.GetLogDetail(uint(id))
	if err != nil {
		logger.Error("获取操作日志详情失败", "logId", id, "error", err.Error())

		// 根据错误信息返回不同的错误码
		errMsg := err.Error()
		switch errMsg {
		case "操作日志不存在":
			response.Error(c, errcode.NotFound, errMsg)
		default:
			response.Error(c, errcode.InternalError, errMsg)
		}
		return
	}

	// 记录审计日志
	adminID, _ := c.Get("userId")
	logger.LogAudit(logger.AuditLog{
		UserID:    adminID.(uint),
		Action:    "VIEW_OPERATION_LOG_DETAIL",
		Resource:  "operation_log",
		IP:        c.ClientIP(),
		UserAgent: c.GetHeader("User-Agent"),
		Details:   "查看日志ID: " + strconv.FormatUint(id, 10),
	})

	response.Success(c, detail, "获取成功")
}

// Delete 删除操作日志
// @Summary 删除操作日志
// @Tags 操作日志管理
// @Produce json
// @Param id path int true "日志ID"
// @Success 200 {object} response.Response
// @Router /api/v1/operation-logs/{id} [delete]
func (h *OperationLogHandler) Delete(c *gin.Context) {
	// 获取日志ID参数
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		response.Error(c, errcode.BadRequest, "日志ID格式错误")
		return
	}

	// 调用Service层删除
	if err := h.service.DeleteLog(uint(id)); err != nil {
		logger.Error("删除操作日志失败", "logId", id, "error", err.Error())

		// 根据错误信息返回不同的错误码
		errMsg := err.Error()
		switch errMsg {
		case "操作日志不存在":
			response.Error(c, errcode.NotFound, errMsg)
		default:
			response.Error(c, errcode.InternalError, errMsg)
		}
		return
	}

	// 记录审计日志
	adminID, _ := c.Get("userId")
	logger.LogAudit(logger.AuditLog{
		UserID:    adminID.(uint),
		Action:    "DELETE_OPERATION_LOG",
		Resource:  "operation_log",
		IP:        c.ClientIP(),
		UserAgent: c.GetHeader("User-Agent"),
		Details:   "删除日志ID: " + strconv.FormatUint(id, 10),
	})

	response.Success(c, nil, "删除成功")
}

// BatchDelete 批量删除操作日志
// @Summary 批量删除操作日志
// @Tags 操作日志管理
// @Accept json
// @Produce json
// @Param body body []uint true "日志ID列表"
// @Success 200 {object} response.Response
// @Router /api/v1/operation-logs/batch [delete]
func (h *OperationLogHandler) BatchDelete(c *gin.Context) {
	// 获取请求体中的ID列表
	var ids []uint
	if err := c.ShouldBindJSON(&ids); err != nil {
		response.Error(c, errcode.BadRequest, "参数错误: "+err.Error())
		return
	}

	// 调用Service层批量删除
	if err := h.service.DeleteBatchLogs(ids); err != nil {
		logger.Error("批量删除操作日志失败", "error", err.Error())

		// 根据错误信息返回不同的错误码
		errMsg := err.Error()
		switch {
		case strings.Contains(errMsg, "不能为空"):
			response.Error(c, errcode.BadRequest, errMsg)
		case strings.Contains(errMsg, "不能超过"):
			response.Error(c, errcode.BadRequest, errMsg)
		default:
			response.Error(c, errcode.InternalError, errMsg)
		}
		return
	}

	// 记录审计日志
	adminID, _ := c.Get("userId")
	logger.LogAudit(logger.AuditLog{
		UserID:    adminID.(uint),
		Action:    "BATCH_DELETE_OPERATION_LOG",
		Resource:  "operation_log",
		IP:        c.ClientIP(),
		UserAgent: c.GetHeader("User-Agent"),
		Details:   "批量删除日志数量: " + strconv.Itoa(len(ids)),
	})

	response.Success(c, nil, "批量删除成功")
}
